<script setup lang="ts">
import { onMounted, ref } from 'vue';
import MButton from '@/libs/Button';
import { type ConfirmProps } from '@/libs/Confirm/types';

const props = withDefaults(defineProps<ConfirmProps>(), {
  confirmText: '确定',
  cancelText: '取消'
});

const isModalVisible = ref<boolean>(false);
const duration = '0.5s';

onMounted(() => {
  showUp();
});

const showUp = () => {
  isModalVisible.value = true;
};

const close = () => {
  isModalVisible.value = false;
  setTimeout(
    () => {
      if (props.close) {
        props.close();
      }
    },
    parseFloat(duration) * 1000
  );
};

const onConfirmClick = () => {
  if (props.confirmHandler) {
    props.confirmHandler();
  }
  close();
};

const onCancelClick = () => {
  if (props.cancelHandler) {
    props.cancelHandler();
  }
  close();
};

defineOptions({ name: 'MConfirm' });
</script>

<template>
  <div>
    <Transition name="modal">
      <div
        v-if="isModalVisible"
        class="fixed top-0 left-0 z-40 h-screen w-screen bg-zinc-900/80"
        @click="close"
      ></div>
    </Transition>
    <Transition name="up-2-down">
      <div
        v-if="isModalVisible"
        class="fixed top-1/3 left-1/2 z-50 w-[80%] -translate-x-1/2 -translate-y-1/2 cursor-pointer rounded-sm border bg-white px-2 py-1.5 xl:w-[35%] dark:border-zinc-600 dark:bg-zinc-800"
      >
        <div class="mb-2 text-lg font-bold text-zinc-500 dark:text-zinc-200">
          {{ props.title }}
        </div>
        <div class="mb-2 text-base text-zinc-900 dark:text-zinc-200">
          {{ props.content }}
        </div>
        <div class="flex items-center justify-end">
          <MButton type="info" @click="onCancelClick" class="mr-2 px-2">
            {{ props.cancelText }}
          </MButton>
          <MButton type="primary" @click="onConfirmClick" class="px-2">
            {{ props.confirmText }}
          </MButton>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style lang="css" scoped>
/* modal 动画 */
.modal-enter-active,
.modal-leave-active {
  transition: all v-bind(duration);
}

/*准备进入, 离开完成*/
.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}

/* up-2-down 动画 */
.up-2-down-enter-active,
.up-2-down-leave-active {
  transition: all v-bind(duration);
}

/*准备进入, 离开完成*/
.up-2-down-enter-from,
.up-2-down-leave-to {
  opacity: 0;
  transform: translate3d(0, 100px, 0);
}
</style>
